<template>
  <div>
    <!-- 以下需配置上传地址 -->
    <el-upload
      action="127.0.0.1:8000/upload_file/image"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="handleUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import { uploadimage, getimageList } from "@/api/file";
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: [],
      dialogImageId: [],
      dialogVisible: false
    };
  },
  created() {
    this.getimageList();
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUpload(file) {
      console.log(file);
      uploadimage(file).then(response => {
        const resp = response;
        console.log(resp);
        if (resp.flag) {
          this.$message({
            type: "success",
            message: "图片上传成功"
          });
          this.getimageList();
        } else {
          this.$message({
            message: resp.message,
            type: "warning"
          });
        }
      });
    },
    getimageList() {
      getimageList().then(response => {
        response.data.forEach(item => {
          this.dialogImageUrl.push(
            "http://127.0.0.1:8001/media/" + item.file_path
          );
          this.dialogImageId.push(item.id);
        });
        var imgList = [];
        for (var i = 0; i < this.dialogImageUrl.length; i++) {
          imgList.push(this.dialogImageUrl[i]);
        }
        this.fileList = imgList.map(ele => {
          let item = {};
          item.url = ele;
          return item;
        });
      });
    }
  }
};
</script>
